package hhh.app.presenter.model.productlist;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.example.view.ExpandTabView;
import com.example.view.ViewMiddle;
import com.example.view.ViewRight;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;
import com.zhy.adapter.recyclerview.wrapper.LoadMoreWrapper;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import hhh.app.R;
import hhh.app.common.Code;
import hhh.app.common.L;
import hhh.app.data.bean.Category;
import hhh.app.data.bean.Product;
import hhh.app.presenter.model.productdetail.ProductDetailActivity;
import hhh.app.presenter.ui.adapter.ItemClickListener;
import hhh.app.presenter.ui.adapter.ProductListAdapter;
import hhh.app.presenter.ui.base.BaseFragment;
import hhh.app.presenter.ui.view.CategoryView;
import hhh.app.presenter.ui.view.SortView;

/**
 * Created by hhh on 2016/12/22.
 */
public class ProductListFragment extends BaseFragment implements ProductListContract.IProductListView, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recyView)
    RecyclerView recyView;
    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout swiperefresh;
    @BindView(R.id.expandtabview)
    ExpandTabView expandtabview;

    private List<Product> products;
    private List<Category> categories;

    private int start = 0;
    private String word = "";
    private final int MODE_REFRESH = 0;
    private final int MODE_LOADING = 1;
    private int mode;
    private int categoryId=-1;
    private String sort="";
    private boolean isLoadend=false;

    private LinearLayoutManager layoutManager;
//    private ProductListAdapter adapter;
    private EmptyWrapper wrapper;
    private LoadMoreWrapper mLoadMoreWrapper;
    private View loadView;
    private View emptyView;

    private ArrayList<View> mViewArray = new ArrayList<View>();

    private ViewMiddle viewMiddle;
    private ViewRight viewRight;
    private ArrayList<String> groups = new ArrayList<String>();
    private SparseArray<LinkedList<String>> children = new SparseArray<LinkedList<String>>();

    private CategoryView categoryView;
    private SortView sortView;

    @Inject
    ProductListPresenter mPrensenter;

    @Override
    protected void init() {
        ((ProductListActivity) getActivity()).getComponent().inject(this);

        products = new ArrayList<Product>();
        categories = new ArrayList<Category>();

        initRecyView();
        initExpandTabView();

    }

    private void initRecyView(){

        swiperefresh.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_light),
                getResources().getColor(android.R.color.holo_green_light),
                getResources().getColor(android.R.color.holo_red_light),
                getResources().getColor(android.R.color.holo_orange_light));
        swiperefresh.setOnRefreshListener(this);
        swiperefresh.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

//        adapter = new ProductListAdapter(getContext(),R.layout.layout_list_item,products);

        loadView= LayoutInflater.from(getContext()).inflate(R.layout.default_loading,null);
        mLoadMoreWrapper=new LoadMoreWrapper(new ProductListAdapter(getContext(),R.layout.layout_list_item,products));
        mLoadMoreWrapper.setLoadMoreView(loadView);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                L.d("loadmore listener");
                if(!isLoadend) {
                   // start++;
                    mPrensenter.loadProducts(start , categoryId, word, sort);
                }
            }
        });
        emptyView=LayoutInflater.from(getContext()).inflate(R.layout.empty_view,null);
        wrapper=new EmptyWrapper(mLoadMoreWrapper);
        wrapper.setEmptyView(R.layout.empty_view);

        layoutManager = new LinearLayoutManager(getContext());
        recyView.setLayoutManager(layoutManager);
        recyView.setItemAnimator(new DefaultItemAnimator());
//        recyView.setAdapter(adapter);
        recyView.setAdapter(wrapper);
        recyView.addOnItemTouchListener(new ItemClickListener(recyView, new ItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(position>=products.size()){
                    return;
                }
                Intent intent=new Intent(getContext(), ProductDetailActivity.class);
//                intent.putExtra("pid",products.get(position).getId());
                Bundle bundle=new Bundle();
                bundle.putParcelable("product",products.get(position));
                intent.putExtra("product",bundle);
                startActivity(intent);
//                ProductDetailFragment fragment=new ProductDetailFragment();
//                Bundle bundle=new Bundle();
//                bundle.putInt("pid",products.get(position).getId());
//                fragment.setArguments(bundle);
//                ((ProductListActivity)(getActivity())).switchFragment(fragment);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        }));
    }

    private void initExpandTabView() {

        categoryView=new CategoryView(getContext());
        sortView=new SortView(getContext());
        mViewArray.add(categoryView);
        mViewArray.add(sortView);

        ArrayList<String> mTexts=new ArrayList<String>();
        mTexts.add("全部");
        mTexts.add("默认");
        expandtabview.setValue(mTexts,mViewArray);

        expandtabview.setTitle(categoryView.getShowText(),0);
        expandtabview.setTitle(sortView.getShowText(),1);

        categoryView.setOnSelectListener(new CategoryView.OnSelectListener() {
            @Override
            public void onSelectListener(int val) {
                categoryId=val;
                if(expandtabview.getTitle(0).equals(categoryView.getShowText())){
                    expandtabview.onPressBack();
                }else{
                    isLoadend=false;
                    start=0;
                    expandtabview.setTitle(categoryView.getShowText(),0);
                    expandtabview.onPressBack();
                    products.clear();
                    mPrensenter.loadProducts(start,val,word,sort);
                }

            }
        });
        sortView.setOnSelectListener(new SortView.OnSelectListener() {
            @Override
            public void onSelectListener(String val) {
                expandtabview.setTitle(sortView.getShowText(),1);
                expandtabview.onPressBack();
                start=0;
                mPrensenter.loadProducts(start,categoryId,word,sort);
            }
        });
    }

    private void onRefresh(View view, String showText) {

        expandtabview.onPressBack();
        int position = getPositon(view);
        if (position >= 0 && !expandtabview.getTitle(position).equals(showText)) {
            expandtabview.setTitle(showText, position);
        }
//        Toast.makeText(MainActivity.this, showText, Toast.LENGTH_SHORT).show();

    }

    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView) {
                return i;
            }
        }
        return -1;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPrensenter.attachView(this);
        if (savedInstanceState == null) {
            mPrensenter.loadCategories();
            //this.onRefresh();
        }
//        mPrensenter.loadCategories();
//        this.onRefresh();
    }

    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_productlist;
    }

    @Override
    public void showProducts(List products) {
        L.d("showProducts");
        swiperefresh.setRefreshing(false);
        int s=products.size();
        if(s>0){
            start+=s;
        }
//        super.showContent();
        if(s< Code.LIMIT){
            isLoadend=true;
            if(s>0) {
                this.products.addAll(products);
            }
            loadView.findViewById(R.id.loading_progress).setVisibility(View.GONE);
            ((TextView)loadView.findViewById(R.id.loading_text)).setText("已经到底了");
//            mLoadMoreWrapper.setLoadMoreView(R.layout.view_loadend);
        }else {
            this.products.addAll(products);
            loadView.findViewById(R.id.loading_progress).setVisibility(View.VISIBLE);
            ((TextView)loadView.findViewById(R.id.loading_text)).setText("正在加载...");
//            mLoadMoreWrapper.setLoadMoreView(R.layout.default_loading);
        }

        wrapper.notifyDataSetChanged();

    }

    @Override
    public void initCategories(Map<Integer, List<Category>> mapCaterory) {
        categoryView.setKeyCategory(mapCaterory);
    }

    @Override
    public void onRefresh() {
        L.d("onrefresh");

        start = 0;
        isLoadend=false;
//        mode = MODE_REFRESH;
        if(this.products.size()!=0){
            this.products.clear();
        }

        mPrensenter.loadProducts(start,categoryId, word, sort);

    }

}
